package com.novel.core.auth;

import com.novel.core.common.constant.ErrorCodeEnum;
import com.novel.core.common.exception.BusinessException;
import com.novel.core.constant.ApiRouterConsts;
import com.novel.core.constant.SystemConfigConsts;
import com.novel.core.util.JwtUtils;
import com.novel.dto.AdminDto;
import com.novel.manager.cache.AdminCacheManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;

/**
 * 平台后台管理系统 认证授权策略
 *
 * @author wang
 */

@Component
@Slf4j
@RequiredArgsConstructor
public class BackendAuthStrategy implements AuthStrategy {

    private final JwtUtils jwtUtils;

    private final AdminCacheManager adminCacheManager;

    /**
     * 不需要进行权限认证的 URI
     */
    private static final List<String> EXCLUDE_URI = List.of(
            ApiRouterConsts.API_ADMIN_URL_PREFIX + "/login"
//            ApiRouterConsts.API_ADMIN_URL_PREFIX + "/**"
    );

    @Override
    public void auth(String token, String requestUri) throws BusinessException {

        if (EXCLUDE_URI.contains(requestUri)) {
            // 该请求不需要进行管理员权限认证
            return;
        }

        // 管理员认证
        if (!StringUtils.hasText(token)) {
            // token为空
            throw new BusinessException(ErrorCodeEnum.ADMIN_LOGIN_EXPIRED);
        }

        Long adminId = jwtUtils.parseToken(token, SystemConfigConsts.NOVEL_ADMIN_KEY);
        log.info("获取管理员ID：{}",adminId);

        if (Objects.isNull(adminId)) {
            // token 为空
            throw new BusinessException(ErrorCodeEnum.ADMIN_LOGIN_EXPIRED);
        }

        AdminDto adminInfo = adminCacheManager.getAdmin(adminId);
        log.info("获取管理员信息：{}",adminInfo);
        if (Objects.isNull(adminInfo)) {
            // 管理员账号不存在
            throw new BusinessException(ErrorCodeEnum.USER_ACCOUNT_NOT_EXIST);
        }

        // 设置 adminId 到当前线程
        UserHolder.setAdminIdTl(adminId);
    }
}